﻿using Anke.SHManage.BLL;
using Anke.SHManage.Model;
using Anke.SHManage.Utility;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Anke.SHManage.Web.Areas.BM.Controllers
{
    [SkipLoginAttribute]
    public class LoginController : Controller
    {
        private string YBInterfaceType = ConfigurationManager.AppSettings["YBInterfaceType"].ToString();//2023-06-14 zch 医保接口方式 
        //
        // GET: /BM/Login/

        //public ActionResult Index()
        //{
        //    string name = Request.Form["username"].ToString();
        //    string pw = Request.Form["passWord"].ToString();
        //    string imei = Request.Form["imei"].ToString();

        //    //首先检查用户名密码
        //    LoginUserBLL bll = new LoginUserBLL();
        //    if (bll.Login(name, pw))
        //    {
        //        string username = UserOperateContext.Current.Session_UsrInfo.Name;
        //        string workCode = UserOperateContext.Current.Session_UsrInfo.WorkCode;
        //        string role = UserOperateContext.Current.getMaxPerForRole();//获取登录人角色(医生、护士、司机)
        //        //登录成功，跳转到主页面
        //        return Json(new { msg = "OK", UName = username, WorkCode = workCode, Role = role }, "appliction/json", JsonRequestBehavior.AllowGet);
        //    }
        //    else
        //    {
        //        //登录失败,发送错误错误给用户
        //        return Json(new { msg = "Error" }, "appliction/json", JsonRequestBehavior.AllowGet);
        //    }
        //}
        
        //edit 2023-06-14 plq 登录接口，新增登录失败次数限制，及失败result字段返回，参考闵行
        public ActionResult Index()
        {
            try
            {
                string name = Request.Form["username"].ToString();
                string pw = Request.Form["passWord"].ToString();
                string imei = Request.Form["imei"].ToString();
                //string version = Request.Form["version"].ToString();

                //首先检查用户名密码
                LoginUserBLL bll = new LoginUserBLL();
                int LoginErrCount = 1; //增加登录失败m次后n分钟内限制登录的功能 add2021-09-23 plq
                DateTime datatimes = DateTime.Now;
                //查询是否重复登录失败次数
                P_Login_Err errInfo = bll.GetLoginErrInfo(name);
                if (errInfo != null)
                {
                    datatimes = errInfo.LoginTime;//最后一次登录失败的时间
                    LoginErrCount = errInfo.LoginErrNum + 1;
                }
                int datediff = Timediff(datatimes);
                //获取登录次数，禁止登录时间分钟；
                int LoginFailCount = AppConfig.GetConfigInt("FailCount");
                int LoginFailStopTime = AppConfig.GetConfigInt("FailStopTime");
                if (LoginErrCount > LoginFailCount && (datediff < LoginFailStopTime))
                {
                    StateLog("登录已锁定", name);//20151117增加状态日志--20160929注释
                    return Json(new { msg = "Error", result = "用户登录" + LoginFailCount + "次失败" + "；请等待" + (LoginFailStopTime - datediff) + "分钟！", Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }, "appliction/    json", JsonRequestBehavior.AllowGet);
                }
                else
                {
                    if (datediff >= LoginFailStopTime) // 登录失败多次后的禁止登录时间已过，失败次      数重新累计
                    {
                        bll.LoginClearErrCount(name, "PAD");
                        LoginErrCount = 1;
                    }
                    //string loginResult = bll.LoginForapp(name, pw, imei, version);
                    //if (loginResult == "") //用户验证通过，登录成功
                    if (bll.Login(name, pw))
                    {
                        StateLog("登录成功", name);//20151117增加状态日志--20160929注释
                        //成功登录，清除错误登录数据 add2021-09-22 plq
                        bll.LoginClearErr(name);
                        string username = UserOperateContext.Current.Session_UsrInfo.Name;
                        string workCode = UserOperateContext.Current.Session_UsrInfo.WorkCode;
                        string role = UserOperateContext.Current.getMaxPerForRole();//获取登录人角色(医生、护士、司机)
                        //登录成功
                        return Json(new { msg = "OK", UName = username, WorkCode = workCode, Role = role, Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), YBInterfaceType = YBInterfaceType }, "appliction/json", JsonRequestBehavior.AllowGet);
                    }
                    else//用户验证失败
                    {
                        StateLog("登录失败", name);//20151117增加状态日志--20160929注释
                        //数据库记录一次登录失败
                        bll.LoginErrCount(name, "PAD");//20160929注释数据库记录一次登录失败);
                        return Json(new { msg = "Error", result = "工号或者密码错误！用户登录" + LoginErrCount + "次失败" + "；请重新输入！", Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }, "appliction/json", JsonRequestBehavior.AllowGet);
                    }
                    //else if (loginResult == "登陆失败:用户名或密码错误!")//用户验证失败
                    //{
                    //    StateLog("登录失败", name);//20151117增加状态日志--20160929注释
                    //    //数据库记录一次登录失败
                    //    bll.LoginErrCount(name, "PAD");//20160929注释数据库记录一次登录失败);
                    //    return Json(new { msg = "Error", result = "工号或者密码错误！用户登录" + LoginErrCount + "次失败" + "；请重新输入！", Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }, "appliction/json", JsonRequestBehavior.AllowGet);
                    //}
                    //else
                    //{
                    //    //登录失败,发送错误错误给用户
                    //    return Json(new { msg = "Error", result = loginResult, Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }, "appliction/  json", JsonRequestBehavior.AllowGet);
                    //}
                }
            }
            catch (Exception e)
            {
                LogUtility.Error("Login/Index", "PAD登录异常！" + e);
                return Json(new { msg = "Error", result = e, Date = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") }, "appliction/json", JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 计算该时间到当前时间的时间间隔(分钟数)
        /// add2021-09-21 plq
        /// </summary>
        /// <param name="t0"></param>
        /// <returns></returns>
        private int Timediff(DateTime t0)
        {
            DateTime t1 = DateTime.Now;
            TimeSpan ts = t1 - t0;
            return (int)(ts.TotalMinutes);
        }

        //20151117增加状态日志
        public int StateLog(string Description, string LoginName)
        {
            TStateLog model = new TStateLog();//20151117增加登录状态日志
            model.Description = Description;//状态
            model.OperationTime = DateTime.Now;//时间
            model.OperationPerson = LoginName;//操作人
            int res = new TStateLogBLL().Add(model.ToPOCO());
            return res;
        }

        ////  /BM/Login/LoginOut
        ////2016-11-28 zch for app loginOut
        //public ActionResult LoginOut(string workCode)
        //{
        //    //根据workcode去user表中删除imei
        //    //成功返回OK,错误error
        //    LoginUserBLL bll = new LoginUserBLL();
        //    string result = bll.deleteIMEI(workCode);
        //    if (result == "")
        //        return Json(new { msg = "OK" }, "appliction/json", JsonRequestBehavior.AllowGet);
        //    else
        //        return Json(new { msg = "Error", Content = result }, "appliction/json", JsonRequestBehavior.AllowGet);
        //}

        public ActionResult text()
        {
            return View();
        }

        /// <summary>
        /// 补打发票登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Denglu()
        {
            string name = Request.Form["username"].ToString();
            string pw = Request.Form["passWord"].ToString();
            string imei = Request.Form["imei"].ToString();

            //首先检查用户名密码
            LoginUserBLL bll = new LoginUserBLL();
            if (bll.Login(name, pw))
            {
                string username = UserOperateContext.Current.Session_UsrInfo.Name;
                string workCode = UserOperateContext.Current.Session_UsrInfo.WorkCode;
                int ID = UserOperateContext.Current.Session_UsrInfo.ID;//用户编码
                string centerCode = "1000";
                //PAD补打发票：只能查看本分中心的人员角色编码
                if (LatePlayRole("LatePlayAllRole"))
                {
                    centerCode = "";
                    return Json(new { msg = "OK", UName = username, WorkCode = workCode, CenterCode = centerCode }, "appliction/json", JsonRequestBehavior.AllowGet);
                }
                else if (LatePlayRole("LatePlayRole"))
                {
                    MobileTaskBLL mtBLL = new MobileTaskBLL();
                    mtBLL.GetCenterCode(workCode, out centerCode);//根据工号获取中心编码

                    //PAD补打发票：查看全部信息的人员角色编码
                    //if (LatePlayRole("LatePlayAllRole"))
                    //{
                    //    centerCode = "";
                    //}
                    //登录成功，跳转到主页面
                    return Json(new { msg = "OK", UName = username, WorkCode = workCode, CenterCode = centerCode }, "appliction/json", JsonRequestBehavior.AllowGet);
                }
                else
                    return Json(new { msg = "没有权限" }, "appliction/json", JsonRequestBehavior.AllowGet);

            }
            else
            {
                //登录失败,发送错误错误给用户
                return Json(new { msg = "登录失败" }, "appliction/json", JsonRequestBehavior.AllowGet);
            }
        }

        #region 判断登录人是否有补打发票权限
        public bool LatePlayRole(string Roles)
        {
            string strSuperRole = AppConfig.GetConfigString(Roles);
            string[] tcr = strSuperRole.Split(',');
            bool tarray = false;
            for (int i = 0; i < tcr.Length; i++)
            {
                bool UserRole = UserOperateContext.Current.Session_UsrRole.SingleOrDefault(p => p == Convert.ToInt32(tcr[i])) != 0 ? true : false;
                if (UserRole)
                {
                    //判断登录人角色
                    tarray = true;
                    break;
                }
            }
            return tarray;
        }
        #endregion
    }
}
